<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/4
 * Time: 16:28
 */

namespace api\modules\v1\controllers;


use common\business\EhrHelper;
use common\consts\Consts;
use common\helpers\DateHelper;
use common\helpers\StringUtil;
use common\models\kingdee\HrPersonPhoto;
use common\models\kingdee\OrgAdmin;
use common\models\kingdee\OrgPosition;
use common\models\kingdee\Person;
use common\models\kingdee\PersonPosition;
use common\models\User;
use yii\db\Exception;
use yii\db\Query;
use yii\filters\auth\QueryParamAuth;
use yii\filters\RateLimiter;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\rest\ActiveController;
use Yii;
use yii\web\Response;

class EmployeesController extends ActiveController
{
    public $modelClass = 'common\models\Employee';

    public function behaviors()
    {
        $behaviors = parent::behaviors();

        $behaviors['rateLimiter'] = [
            'class' => RateLimiter::className(),
            'enableRateLimitHeaders' => true,
        ];

//        是否要验证
//        $behaviors['authenticator'] = [
//            'class' => CompositeAuth::className(),
//            'authMethods' => [
//                /*下面是三种验证access_token方式*/
//                //1.HTTP 基本认证: access token 当作用户名发送，应用在access token可安全存在API使用端的场景，例如，API使用端是运行在一台服务器上的程序。
//                //HttpBasicAuth::className(),
//                //2.OAuth 2: 使用者从认证服务器上获取基于OAuth2协议的access token，然后通过 HTTP Bearer Tokens 发送到API 服务器。
//                //HttpBearerAuth::className(),
//                //3.请求参数: access token 当作API URL请求参数发送，这种方式应主要用于JSONP请求，因为它不能使用HTTP头来发送access token
//                //http://localhost/user/index/index?access-token=123
//                QueryParamAuth::className(),
//            ],
//        ];

//        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
//        return $behaviors;

        return ArrayHelper::merge (parent::behaviors(), [
            'authenticator' => [
                'class' => QueryParamAuth::className(),
                'optional' => [
                    'list-by-org',
                    'list-by-token',
                    'detail-by-token',
                    'org-chain-by-number',
                ],
            ],
        ] );
    }

    public function actions()
    {
        $actions = parent::actions();
        // 禁用""index,delete" 和 "create" 操作
        unset($actions['index'], $actions['delete'], $actions['create']);
        return $actions;
    }

    protected function getListByOrg($offset = 0, $limit = 10, $org_id = '', $search_val = '') {
        $db = Person::getDb();
        $org_id = urldecode(stripslashes($org_id));

        if (strtolower($org_id) == 'null' || strtolower($org_id) == 'undefined') {
//            $org_id = '';
            return [
                'count' => 0,
                'data' => [],
            ];
        }

        if (!StringUtil::isNullOrWhiteSpace($org_id)) {
            $org = OrgAdmin::findOne([
                'FID' => $org_id
            ]);

            $orgIdParams = [
                'fid' => $org->FID
            ];
            $cmd = $db->createCommand('SELECT t.fid FROM T_ORG_ADMIN t START WITH t.fid = :fid CONNECT BY t.fparentid = PRIOR fid', $orgIdParams);
//        $cmd->bindParam('fid', $orgId);
            try {
                $orgIdArr = $cmd->queryColumn();
            } catch (Exception $e) {
                return [];
            }
        }

        $query = (new Query())->from('T_BD_PERSON TBP')
            ->leftJoin('T_BD_HRWED TBWED', 'TBWED.FID = TBP.FWEDID')
            ->leftJoin('T_BD_NATIONALITY NAT', 'NAT.FID = TBP.FNATIONALITYID')
            ->leftJoin('T_BD_HRFOLK FK', 'FK.FID = TBP.FFOLKID')
            ->leftJoin('T_BD_REGPERMRESIDENCE REGP', 'REGP.FID = TBP.FREGRESIDENCEID')
            ->leftJoin('T_HR_PERSONCONTACTMETHOD THPCM', 'THPCM.FPERSONID = TBP.FID')
            ->leftJoin('T_HR_PERSONPOSITION THPP', 'THPP.FPERSONID = TBP.FID')
            ->leftJoin('T_ORG_POSITION TOPP', 'TOPP.FID = THPP.FPRIMARYPOSITIONID')
            ->leftJoin('T_HR_EMPLABORRELATION THELR', 'THELR.FPERSONID = TBP.FID')
            ->leftJoin('T_HR_BDEMPLOYEETYPE THBET', 'THBET.FID = THELR.FLABORRELATIONSTATEID')
            ->leftJoin('T_ORG_ADMIN TOA', 'TOA.FID = TOPP.FADMINORGUNITID')
            ->leftJoin('T_BD_HRDIPLOMA TBDIP', 'TBP.FHIGHESTDEGREEID = TBDIP.FID')
            ->select([
                'id' => 'TBP.FID',
                'name' => 'TBP.FNAME_L2',
                'number' => 'TBP.FNUMBER',
                'gender' => 'TBP.FGENDER',
                'birthday' => 'to_char(FBIRTHDAY , \'yyyy-MM-dd\')',
                'email' => 'TBP.FEMAIL',
                'home_phone' => 'TBP.FHOMEPHONE',
                'mobile' => 'TBP.FCELL',
                'id_card_num' => 'TBP.FIDCARDNO',
                'native_place' => 'TBP.FNATIVEPLACE_L2',
                'blood_type' => 'TBP.FBLOODTYPE',
                'wed_status' => 'TBWED.FNAME_L2',
                'nationality' => 'NAT.FNAME_L2',
                'folk' => 'FK.FNAME_L2',
                'hklx' => 'REGP.FNAME_L2',
                'hr_id' => 'TBP.FID',
                'weixin' => 'THPCM.FWEIXIN',
                'position_name' => 'TOPP.FNAME_L2',
                'position_number' => 'TOPP.FNUMBER',
                'labor_relation_state' => 'THBET.FNAME_L2',
                'department_name' => 'TOA.FNAME_L2',
                'department_number' => 'TOA.FNUMBER',
                'department_display_name' => 'TOA.FDISPLAYNAME_L2',
                'highest_degree' => 'TBDIP.FNAME_L2',
            ]);
//        if (!StringUtil::isNullOrWhiteSpace($org_id)) {
//            $query->andFilterWhere([
//                'in', 'THPP.FPERSONDEP', $orgIdArr
//            ]);
//        }
//        $query->where(['THBET.FISONTHESTRENTH' => 1]);
        $query->andFilterWhere(['THBET.FISINCOUNT' => 1]);
        $query->andFilterWhere([
            'TOA.FID' => $org_id,
        ]);
        if (!StringUtil::isNullOrWhiteSpace($search_val) && strtolower($search_val) !== 'null' && strtolower($search_val) !== 'undefined') {
            $query->andFilterWhere([
                'like', 'TBP.FNAME_L2', $search_val
            ]);
        }
        $query->orderBy([
            'TBP.FNUMBER' => SORT_ASC,
        ]);

//        $totalCount = $query->count('*', $db);
        $all = $query->offset($offset)->limit($limit)->all($db);

        foreach ($all as &$item) {
            $personPhoto = HrPersonPhoto::findOne([
                'FPERSONID' => $item['id'],
            ]);
            if (!$personPhoto) {
                $imageName = $item['gender'] == Consts::GENDER_MALE ? 'male_unknown.jpg' : 'female_unknown.jpg';
                $item['src'] = Url::to("@web/images/$imageName");
            } else {
                $item['src'] = EhrHelper::getPersonPhoto($personPhoto);
            }
            $item['id'] = urlencode($item['id']);
        }

        return [
            'count' => count($all),
            'data' => $all,
        ];
    }

    /**根据组织节点的id拿到组织下所有员工的列表
     * @param integer $offset
     * @param integer $limit
     * @param string $org_id
     * @param string $search_val
     * @return array
     */
    public function actionListByOrg($offset = 0, $limit = 10, $org_id = '', $search_val = '')
    {
        return $this->getListByOrg($offset, $limit, $org_id, $search_val);
    }

    /**根据组织节点的id拿到组织下所有员工的列表,专门供第三方接口使用，需要检查access_token
     * @param int $offset
     * @param int $limit
     * @param string $org_id
     * @param string $search_val
     * @param null $access_token
     * @return
     */
    public function actionListByToken($offset = 0, $limit = 10, $org_id = '', $search_val = '', $access_token = null)
    {
        if (!EhrHelper::checkAccessTokenIsValid($access_token)) {
            return [
                'count' => 0,
                'data' => ['access_token不正确或者已过期'],
            ];
        }
        $arr =  $this->getListByOrg($offset, $limit, $org_id, $search_val);
//        var_dump($arr);
        return $arr;
    }

    /**
     * @return Query
     */
    protected function getPersonBaseQuery()
    {
        $query = (new Query())->from('T_BD_PERSON TBP')
            ->leftJoin('T_BD_HRWED TBWED', 'TBWED.FID = TBP.FWEDID')
            ->leftJoin('T_BD_NATIONALITY NAT', 'NAT.FID = TBP.FNATIONALITYID')
            ->leftJoin('T_BD_HRFOLK FK', 'FK.FID = TBP.FFOLKID')
            ->leftJoin('T_BD_HRHEALTH TBHRH', 'TBP.FHEALTHID = TBHRH.FID')
            ->leftJoin('T_BD_REGPERMRESIDENCE REGP', 'REGP.FID = TBP.FREGRESIDENCEID')
            ->leftJoin('T_HR_PERSONCONTACTMETHOD THPCM', 'THPCM.FPERSONID = TBP.FID')
            ->leftJoin('T_HR_PERSONPOSITION THPP', 'THPP.FPERSONID = TBP.FID')
            ->leftJoin('T_ORG_POSITION TOPP', 'TOPP.FID = THPP.FPRIMARYPOSITIONID')
            ->leftJoin('T_HR_EMPLABORRELATION THELR', 'THELR.FPERSONID = TBP.FID')
            ->leftJoin('T_HR_BDEMPLOYEETYPE THBET', 'THBET.FID = THELR.FLABORRELATIONSTATEID')
            ->leftJoin('T_ORG_ADMIN TOA', 'TOA.FID = TOPP.FADMINORGUNITID')
            ->leftJoin('T_BD_HRDIPLOMA TBDIP', 'TBP.FHIGHESTDEGREEID = TBDIP.FID')
            ->select([
                'id' => 'TBP.FID',
                'name' => 'TBP.FNAME_L2',
                'number' => 'TBP.FNUMBER',
                'gender' => 'TBP.FGENDER',
                'birthday' => 'to_char(TBP.FBIRTHDAY , \'yyyy"年"MM"月"dd"日"\')',
                'age' => '(extract(year from sysdate) - extract(year from TBP.FBIRTHDAY))',
                'email' => 'TBP.FEMAIL',
                'mobile' => 'TBP.FCELL',
                'id_card_num' => 'TBP.FIDCARDNO',
                'native_place' => 'TBP.FNATIVEPLACE_L2',
                'blood_type' => 'TBP.FBLOODTYPE',
                'rdtsj' => 'to_char(TBP.CFRDTSJ , \'yyyy"年"MM"月"dd"日"\')',
                'wed_status' => 'TBWED.FNAME_L2',
                'nationality' => 'NAT.FNAME_L2',
                'folk' => 'FK.FNAME_L2',
                'hklx' => 'REGP.FNAME_L2',
                'hr_id' => 'TBP.FID',
                'weixin' => 'THPCM.FWEIXIN',
                'qq' => 'THPCM.FQQ',
//                'email' => 'THPCM.FEMAIL',
                'home_place' => 'TBP.FHOMEPLACE',
                'hj_address' => 'TBP.FHJADDRESS',
                'id_card_address' => 'TBP.FIDCARDADDRESS',
                'gatxz' => 'TBP.CFGATXZ',
                'pttxz' => 'TBP.CFPTTXZ',
                'passport_no' => 'TBP.FPASSPORTNO',
                'health' => 'TBHRH.FNAME_L2',
                'home_address' => 'THPCM.FHOMEADDRESS',
                'position_name' => 'TOPP.FNAME_L2',
                'position_number' => 'TOPP.FNUMBER',
                'labor_relation_state' => 'THBET.FNAME_L2',
                'department_id' => 'TOA.FID',
                'department_name' => 'TOA.FNAME_L2',
                'department_number' => 'TOA.FNUMBER',
                'department_display_name' => 'TOA.FDISPLAYNAME_L2',
                'highest_degree' => 'TBDIP.FNAME_L2',
                'sdh' => 'TBP.CFSDH',
                'is_in_count' => 'THBET.FISINCOUNT',
            ]);
        return $query;
    }


    /**
     * @param $id string
     * @return array
     */
    protected function getCompanyExperiences($id){
        $query = (new Query())->from('T_HR_EMPORGRELATION THEOR')
            ->leftJoin('T_BD_PERSON TBP', 'THEOR.FPERSONID = TBP.FID')
            ->leftJoin('T_ORG_POSITION TOP', 'TOP.FID = THEOR.FPOSITIONID')
            ->leftJoin('T_HR_EMPLABORRELATION THELR', 'THELR.FID = THEOR.FLABORRELATIONID')
            ->leftJoin('T_HR_BDEMPLOYEETYPE THBET', 'THBET.FID = THELR.FLABORRELATIONSTATEID')
            ->leftJoin('T_ORG_ADMIN TOA', 'TOA.FID = TOP.FADMINORGUNITID')
            ->leftJoin('T_HR_AFFAIRACTIONREASON THAAR', 'THAAR.FID = THEOR.FACTIONTYPEID')
            ->select([
                'idx' => 'THEOR.FID',
//                'name' => 'TBP.FNAME_L2',
//                'number' => 'TBP.FNUMBER',
                'start_date' => 'to_char(THEOR.FEFFDT , \'yyyy"年"MM"月"\')',
                'end_date' => 'to_char(THEOR.FLEFFDT , \'yyyy"年"MM"月"\')',
                'end_date_pure' => 'to_char(THEOR.FLEFFDT , \'yyyy-MM-dd hh24:mi:ss\')',
                'position_name' => 'TOP.FNAME_L2',
                'department_display_name' => 'TOA.FDISPLAYNAME_L2',
                'labor_relation_state' => 'THBET.FNAME_L2',
                'department_txt' => 'THEOR.FADMINORGTXT',
                'position_text' => 'THEOR.FPOSITIONTXT',
                'action_type' => 'THAAR.FNAME_L2',
            ])->where(['TBP.FID' => $id])->orderBy(['THEOR.FEFFDT' => SORT_DESC]);

        $all = $query->all(Person::getDb());
        foreach ($all as &$item) {
            if (StringUtil::isNullOrWhiteSpace($item['department_display_name'])){
                $item['department_display_name'] = $item['department_txt'];
            }
            if (StringUtil::isNullOrWhiteSpace($item['position_name'])){
                $item['position_name'] = $item['position_text'];
            }
            unset($item['department_txt']);
            unset($item['position_text']);
            date_default_timezone_set('PRC'); //设置为东八区时间

            $endDate = strtotime($item['end_date_pure']);

            if (!$endDate || ($endDate > time())){
                $endDateStr = '至今';
            }
            else {
                $endDateStr =  $item['end_date'];
            }

            $item['start_end_date'] = sprintf('%s ~ %s', $item['start_date'], $endDateStr);
        }

        return $all;
    }

    /**
     * @param $id string
     * @return array
     */
    protected function getSocialExperiences($id){
        $query = (new Query())->from('T_HR_PERSONWORKEXP THPWE')
            ->select([
                'idx' => 'THPWE.FID',
                'start_date' => 'to_char(THPWE.FBEGINDATE , \'yyyy"年"MM"月"\')',
                'end_date' => 'to_char(THPWE.FENDDATE , \'yyyy"年"MM"月"\')',
                'position_name' => 'THPWE.FPOSITION',
                'company_name' => 'THPWE.FUNITNAME',
                'department_display_name' => 'THPWE.FWORKDEPT',
                'remark' => 'THPWE.FREMARK',
            ])->where(['THPWE.FPERSONID' => $id])->orderBy(['THPWE.FBEGINDATE' => SORT_DESC]);

        $all = $query->all(Person::getDb());
        foreach ($all as &$item) {
            $item['start_end_date'] = sprintf('%s ~ %s', $item['start_date'], $item['end_date']);
        }

        return $all;
    }

    /**
     * @param $id string
     * @return array
     */
    protected function getEduExperiences($id){
        $query = (new Query())->from('T_HR_PERSONDEGREE THPD')
            ->leftJoin('T_HR_BDSPECIALTYTYPE THDBST', 'THDBST.FID = THPD.fspecialtytype')
            ->leftJoin('T_BD_HRDEGREE TBHD', 'TBHD.FID = THPD.fdegree')
            ->leftJoin('T_BD_HRDIPLOMA TBHDA', 'TBHDA.FID = THPD.fdiploma')
            ->select([
                'idx' => 'THPD.FID',
                'start_date' => 'to_char(THPD.FENROLLDATE , \'yyyy"年"MM"月"\')',
                'end_date' => 'to_char(THPD.FGRADUATEDATE , \'yyyy"年"MM"月"\')',
                'school' => 'THPD.FGRADUATESCHOOL',
                'diploma' => 'TBHDA.FNAME_L2',
                'degree' => 'TBHD.FNAME_L2',
                'specialty_type' => 'THDBST.FNAME_L2',
                'specialty' => 'THPD.FSPECIALTY',
            ])->where(['THPD.FPERSONID' => $id])->orderBy(['THPD.FGRADUATEDATE' => SORT_DESC]);

        $all = $query->all(Person::getDb());
        foreach ($all as &$item) {
            $item['start_end_date'] = sprintf('%s ~ %s', $item['start_date'], $item['end_date']);
        }

        return $all;
    }

    /**
 * @param $id string
 * @return array
 */
    protected function getCertifyCompetencies($id){
        $query = (new Query())->from('T_HR_PERSONCERTIFYCOMPETENCY THPCC')
            ->leftJoin('T_HR_BDCERTIFYCOMPETENCY THBCC', 'THPCC.FCertifiedCompetencyID = THBCC.fid')
            ->leftJoin('T_HR_BDCERTIFYCOMPETENCYTYPE THBCCT', 'THBCC.FCategoryID = THBCCT.fid')
            ->select([
                'idx' => 'THPCC.FID',
                'certify_name' => 'THBCC.FNAME_L2',
                'certify_type' => 'THBCCT.FNAME_L2',
                'zgdj' => 'THPCC.CFZGDJ',
//                'gain_date' => '',
            ])->where(['THPCC.FPERSONID' => $id])->orderBy(['THPCC.FID' => SORT_DESC]);

        $all = $query->all(Person::getDb());
        foreach ($all as &$item) {
            $item['gain_date'] = '';
        }

        return $all;
    }

    /**
     * @param $id string
     * @return array
     */
    protected function getTechPosts($id){
        $query = (new Query())->from('T_HR_PERSONTECHPOST THPTP')
            ->leftJoin('T_HR_BDTECHPOSTTYPE THBTPT', 'THPTP.CFZCLBID = THBTPT.fid')
            ->leftJoin('T_HR_BDTECHPOSTLEVEL THBTPL', 'THPTP.CFZCJBID = THBTPL.fid')
            ->select([
                'idx' => 'THPTP.FID',
                'zcmc' => 'THPTP.CFZC',
                'zyfx' => 'THPTP.CFFX',
                'zclb' => 'THBTPT.FNAME_L2',
                'zcjb' => 'THBTPL.FNAME_L2',
//                'gain_date' => '',
            ])->where(['THPTP.FPERSONID' => $id])->orderBy(['THPTP.CFZC' => SORT_DESC]);

        $all = $query->all(Person::getDb());
        foreach ($all as &$item) {
            $item['gain_date'] = '';
        }

        return $all;
    }

    /**根据id得到员工的详情
     * @param string $id
     * @return array
     */
    public function actionDetail($id)
    {
        $id = urldecode(stripslashes($id));
//        $id = 'HjXW5BPPTtSvN/Mx9TDzXoDvfe0=';
        $query = $this->getPersonBaseQuery()->where(['TBP.FID' => $id]);
//            ->andWhere(['THBET.FISINCOUNT' => 1]);

        $person = $query->one(Person::getDb());

        if (!$person) {
            return [];
        }

        if (!$person['sdh']){
            $person['sdh'] = '否';
        }

        $personPhoto = HrPersonPhoto::findOne([
            'FPERSONID' => $id,
        ]);
        if (!$personPhoto) {
            $imageName = $person['gender'] == Consts::GENDER_MALE ? 'male_unknown.jpg' : 'female_unknown.jpg';
            $person['avatar'] = Url::to("@web/images/$imageName");
        } else {
            $person['avatar'] = EhrHelper::getPersonPhoto($personPhoto);
        }

        $experiences = $this->getCompanyExperiences($id);
        $socialExperiences = $this->getSocialExperiences($id);
        $educationExperiences = $this->getEduExperiences($id);
        $techPosts = $this->getTechPosts($id);
//        $company_experience = [
//            'list'=> $experiences,
//            'pagination' => [
//                'total' => count($experiences),
//                'pageSize' => count($experiences),
//                'current' => 1
//            ]
//        ];
        $certifyCompetencies = $this->getCertifyCompetencies($id);

        return [
            'info' => $person,
            'company_experience' => $experiences,
            'social_experience' => $socialExperiences,
            'education_experience' => $educationExperiences,
            'certify_competency' => $certifyCompetencies,
            'tech_post' => $techPosts,
        ];
    }

    /**根据id得到员工的详情
     * @param string $number 员工号
     * @param string $access_token token号
     * @return array
     */
    public function actionDetailByToken($access_token = '', $number = '')
    {
//        先去掉验证
//        if (!EhrHelper::checkAccessTokenIsValid($access_token)) {
//            return [
//                'count' => 0,
//                'data' => ['access_token不正确或者已过期'],
//            ];
//        }

        $id = EhrHelper::getPersonIdByNumber($number);
//        $id = 'HjXW5BPPTtSvN/Mx9TDzXoDvfe0=';
        $query = $this->getPersonBaseQuery()->where(['TBP.FID' => $id]);

        $person = $query->one(Person::getDb());

        if (!$person) {
            return [];
        }

        if (!$person['sdh']){
            $person['sdh'] = '否';
        }

        $personPhoto = HrPersonPhoto::findOne([
            'FPERSONID' => $id,
        ]);
        if (!$personPhoto) {
            $imageName = $person['gender'] == Consts::GENDER_MALE ? 'male_unknown.jpg' : 'female_unknown.jpg';
            $person['avatar'] = Url::to("@web/images/$imageName");
        } else {
            $person['avatar'] = EhrHelper::getPersonPhoto($personPhoto);
        }

        $experiences = $this->getCompanyExperiences($id);
        $socialExperiences = $this->getSocialExperiences($id);
        $educationExperiences = $this->getEduExperiences($id);
        $techPosts = $this->getTechPosts($id);
//        $company_experience = [
//            'list'=> $experiences,
//            'pagination' => [
//                'total' => count($experiences),
//                'pageSize' => count($experiences),
//                'current' => 1
//            ]
//        ];
        $certifyCompetencies = $this->getCertifyCompetencies($id);

        return [
            'info' => $person,
            'company_experience' => $experiences,
            'social_experience' => $socialExperiences,
            'education_experience' => $educationExperiences,
            'certify_competency' => $certifyCompetencies,
            'tech_post' => $techPosts,
        ];
    }

    public function actionOrgChain($id){
        $id = urldecode(stripslashes($id));
        $query = $this->getPersonBaseQuery()->where(['TBP.FID' => $id])->andWhere(['THBET.FISINCOUNT' => 1]);
        $person = $query->one(Person::getDb());

        if (!$person) return [];
        return EhrHelper::getOrgChain($person['department_id']);
    }

    public function actionOrgChainByNumber($access_token = '', $number = ''){
//        if (!EhrHelper::checkAccessTokenIsValid($access_token)) {
//            return [
//                'count' => 0,
//                'data' => ['access_token不正确或者已过期'],
//            ];
//        }
        $query = $this->getPersonBaseQuery()->where(['TBP.FNUMBER' => $number])->andWhere(['THBET.FISINCOUNT' => 1]);
        $person = $query->one(Person::getDb());

        if (!$person) return [];
        return EhrHelper::getOrgChain($person['department_id']);
    }

    public function actionQueryLeave($offset = 0, $limit = 10, $search_val = '') {
        if ($search_val === 'null'){
            $search_val = '';
        }

        $query = $this->getPersonBaseQuery()->where(['THBET.FISINCOUNT' => 0])
            ->andFilterWhere(['or',
                ['like', 'TBP.FNAME_L2', $search_val],
                ['like', 'TBP.FNUMBER', $search_val]
            ])
            ->orderBy([
            'TBP.FNUMBER' => SORT_ASC,
        ]);

        $all = $query->offset($offset)->limit($limit)->all(Person::getDb());

        foreach ($all as &$item) {
            $personPhoto = HrPersonPhoto::findOne([
                'FPERSONID' => $item['id'],
            ]);
            if (!$personPhoto) {
                $imageName = $item['gender'] == Consts::GENDER_MALE ? 'male_unknown.jpg' : 'female_unknown.jpg';
                $item['src'] = Url::to("@web/images/$imageName");
            } else {
                $item['src'] = EhrHelper::getPersonPhoto($personPhoto);
            }
            $item['id'] = urlencode($item['id']);
        }

        return [
            'count' => count($all),
            'data' => $all,
        ];
    }

    protected function query($offset = 0, $limit = 10, $search_val = '') {

    }

    public function actionGetPhoto($fid){
        $fid = urldecode(stripslashes($fid));
        $person = Person::findOne(['FID' => $fid]);
        $personPhoto = HrPersonPhoto::findOne([
            'FPERSONID' => $fid,
        ]);
        if (!$personPhoto) {
            $imageName = $person->FGENDER == Consts::GENDER_MALE ? 'male_unknown.jpg' : 'female_unknown.jpg';
            $src = Url::to("@web/images/$imageName");
        } else {
            $src = EhrHelper::getPersonPhoto($personPhoto);
        }
        return $src;
//        $returnVal = sprintf('<image src="%s" alt="%s_%s" />', $src, $person->FNUMBER, $person->FNAME_L2);
//        echo $returnVal;
    }
}